import { Form, Input, Toast, Button, InputType, VerifyOutlined, EmailOutlined } from 'esy-ui';
import { Header } from '@/components';
import { form_ipt_com_1 } from '@/styles/esy-ui';
import { useFormatText } from '@/hooks';
import { useGlobalStore, useUserInfoStore } from '@/mobx';
import { postBindEmail } from '@/services';
import SendCode from '../safety/SendCode';

const FormItem = Form.Item;

/** 邮箱绑定 */
const bindEmail = {
  title: 'text_119',
  formItmes: [
    {
      name: 'BindInfo',
      label: 'text_111',
      placeholder: 'text_210',
      maxLength: 99,
      type: 'email',
      before: <EmailOutlined className='absolute left-3 text-split' />,
    },
    {
      name: 'VerfiyCode',
      label: 'text_120',
      placeholder: 'please_code',
      type: 'text',
      isSend: true,
      maxLength: 6,
      before: <VerifyOutlined className='absolute left-3 text-split' />,
    },
  ],
};

function BindEmail() {
  const [form] = Form.useForm();
  const { changeUserInfo } = useUserInfoStore();
  const { text } = useFormatText();
  const { changeState } = useGlobalStore();

  const onSubmit = () => {
    changeState('isLoading', true);
    form
      .validate()
      .then((values) => {
        if (Object.values(values).some((it) => !it)) {
          changeUserInfo({ Email: values.BindInfo } as any);
          Toast.show({ content: text('text_88') });
          changeState('isLoading', false);
        } else {
          postBindEmail(values)
            .then(() => {
              Toast.show({ content: text('text_129') });
            })
            .catch(() => {})
            .finally(() => {
              changeState('isLoading', false);
            });
        }
      })
      .catch(() => {
        changeState('isLoading', false);
      });
  };

  return (
    <div className='bg-white w-full h-full flex flex-col'>
      <Header title={bindEmail.title} />
      <Form form={form} className='px-2.5 py-10'>
        {/* <div className='flex-1'> */}
        {bindEmail.formItmes.map((it) => (
          <FormItem className='mb-5' key={it.name} name={it.name}>
            <Input
              placeholder={text(it.placeholder)}
              type={it.type as InputType}
              classNames={form_ipt_com_1}
              prefix={it.before}
              suffix={it.isSend ? <SendCode form={form} maxLength={it.maxLength} conKey='bindEmail' /> : null}
            />
          </FormItem>
        ))}
        {/* </div> */}
        <Button className='rounded mt-3' htmltype='submit' onClick={onSubmit}>
          {text('text_93')}
        </Button>
      </Form>
    </div>
  );
}

export default BindEmail;
